
#include "ST_LED.h"
#include "ST_TIM3.h"
#include "ST_UART1.h"
#include "ST_IO.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "rtthread.h"

static rt_thread_t led1_thread = RT_NULL;
static rt_thread_t temperature_send_thread = RT_NULL; // Temperature sending thread pointer

static void led1_thread_entry(void* parameter);
static void temperature_send_thread_entry(void* parameter);

// Generate random temperature between 20.0 and 50.0
static float generate_random_temperature(void)
{
    float temp = (float)(rand() % 301) / 10.0f + 20.0f; // 20.0 to 50.0
    return temp;
}

// Convert integer to string (simple implementation)
static void int_to_str(int num, char* str)
{
    int i = 0;
    int is_negative = 0;
    
    if (num < 0) {
        is_negative = 1;
        num = -num;
    }
    
    // Convert to string (reverse order)
    do {
        str[i++] = '0' + (num % 10);
        num /= 10;
    } while (num > 0);
    
    // Reverse the string
    for (int j = 0; j < i/2; j++) {
        char temp = str[j];
        str[j] = str[i-1-j];
        str[i-1-j] = temp;
    }
    
    if (is_negative) {
        // Shift right and add minus sign
        for (int j = i; j > 0; j--) {
            str[j] = str[j-1];
        }
        str[0] = '-';
        i++;
    }
    
    str[i] = '\0';
}

// Send temperature data frame
static void send_temperature_frame(void)
{
    char frame_buffer[1024];
    char temp_str[16];
    int offset = 0;
    
    // Frame header
    memcpy(frame_buffer + offset, "$TEMP", 5);
    offset += 5;
    
    // Generate and add 60 temperature values as strings
    for (int i = 0; i < 60; i++)
    {
        float temp = generate_random_temperature();
        // Convert float to string with 1 decimal place
        int temp_int = (int)(temp * 10);
        int whole_part = temp_int / 10;
        int decimal_part = temp_int % 10;
        if (decimal_part < 0) decimal_part = -decimal_part;
        
        // Format temperature string manually
        int_to_str(whole_part, temp_str);
        int len = 0;
        while (temp_str[len] != '\0') len++;
        
        // Copy whole part
        memcpy(frame_buffer + offset, temp_str, len);
        offset += len;
        
        // Add decimal point
        frame_buffer[offset++] = '.';
        
        // Add decimal part
        frame_buffer[offset++] = '0' + decimal_part;
        
        // Add comma separator (except for last temperature)
        if (i < 59) {
            frame_buffer[offset++] = ',';
        }
    }
    
    // Frame tail
    frame_buffer[offset++] = '\r';
    frame_buffer[offset++] = '\n';
    
    // Send frame via UART
    for (int i = 0; i < offset; i++)
    {
        USART_SendData(USART1, frame_buffer[i]);
        while (USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);
    }
}

int main(void)
{
    // SCB->VTOR = FLASH_BASE | 0x20000;// Vector table
    // IROM1: 0x8020000 0x20000
    // IROM1: 0x8000000 0x80000
    
    //uint32_t start = 0;
    
    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_4);
    
    LedInit();      // LED initialization
    RelayInit();    // Relay initialization
    
    USART1Init(115200);   // Debug interface and relay control
    
    //Timer3Init(10-1,8400-1);// Interrupt period 1ms, previous configuration

    printf("\r\n\r\nSystem Initialized\r\n");
  
    led1_thread = rt_thread_create( 
        "led1",             // Thread name
        led1_thread_entry,  // Thread entry function
        RT_NULL,            // Thread entry parameter
        512,                // Thread stack size
        3,                  // Thread priority
        20);                // Thread time slice
    
    temperature_send_thread = rt_thread_create(
        "temp_send",
        temperature_send_thread_entry,
        RT_NULL,
        512,
        4,                
        20);
    
    
    /* Start threads, start scheduler */
    if (led1_thread != RT_NULL)
    {
        rt_thread_startup(led1_thread);
    }
    else
    {
        return -1;
    }
    
    if (temperature_send_thread != RT_NULL)
    {
        rt_thread_startup(temperature_send_thread);
    }
    else
    {
        return -1;
    }
    
}


static void led1_thread_entry(void* parameter)
{	
    while (1)
    {
        // Red LED ON, Green LED OFF
        SetLedRedOn();
        SetLedGreenOff();
        rt_thread_delay(250);   /* Delay 500 ticks */
        
        // Red LED OFF, Green LED ON
        SetLedRedOff();     
        SetLedGreenOn();
        rt_thread_delay(250);   /* Delay 500 ticks */		 		
    }
}


static void temperature_send_thread_entry(void* parameter)
{
    while (1)
    {
        // Print header
        printf("T: ");
        // Generate and print 60 temperature values
        for (int i = 0; i < 60; i++)
        {
            float temp;
            int col = i / 5;
            if (col == 9) {
                temp = (float)(rand() % 51) / 10.0f + 80.0f; // 80.0~85.0
            } else if (col == 7) {
                temp = (float)(rand() % 301) / 10.0f + 20.0f; // 20.0~50.0
            } else {
                temp = (float)(rand() % 51) / 10.0f + 20.0f; // 20.0~25.0
            }
            printf("%.1f", temp);
            
            if (i < 59) {
                printf(", ");
            } else {
                printf("\r\n");
            }
        }
        
        // Delay 1 second (1000 ticks)
        rt_thread_delay(1000);
    }
}
